package com.itheima.tlias.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.itheima.tlias.Mapper.OperateLogMapper;
import com.itheima.tlias.pojo.OperateLog;
import com.itheima.tlias.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect
public class LogAspect {
    @Pointcut("@annotation(com.itheima.tlias.anno.Log)")
    public void Pt() {
    }

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.itheima.tlias.anno.Log)")
    public Object recodeLog(ProceedingJoinPoint joinPoint) throws Throwable {

        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);
        //获取操作人
        log.info("获取操作人id");
        Integer operateUser = (Integer) claims.get("id");


        //获取操作时间
        log.info("获取操作时间");
        LocalDateTime operateTime = LocalDateTime.now();

        //获取执行方法的全类名，置顶方法名，方法运行时参数，返回值
        log.info("获取执行方法的全类名，置顶方法名，方法运行时参数，返回值");
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);


        Long begin = System.currentTimeMillis();
        Object result = joinPoint.proceed();//运行返回值


        String returnValue = JSONObject.toJSONString(result);
        log.info("返回参数："+result);

        Long end = System.currentTimeMillis();
        Long costTime = end - begin;//方法执行时间

        OperateLog operateLog = new OperateLog(null,operateUser, operateTime, className, methodName, methodParams, returnValue, costTime);
        log.info(null+" "+operateUser+" "+operateTime+" "+className+" "+methodName+" "+methodParams+" "+returnValue+" "+costTime);

        operateLogMapper.insert(operateLog);

        return result;

    }


}
